package com.sun.webmanage.service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.sun.commons.pojo.EasyUIDataGrid;
import com.sun.dubbo.webmanage.service.TbItemCatDubboService;
import com.sun.dubbo.webmanage.service.TbItemParamDubboService;
import com.sun.exception.DaoException;
import com.sun.webmanage.model.TbItemParam;
import com.sun.webmanage.pojo.TbItemParamCustom;

@Service("TbItemParamService")
public class TbItemParamServiceImpl implements TbItemParamService{

	@Reference
	private TbItemParamDubboService tbItemParamDubboService;
	@Reference
	private TbItemCatDubboService tbItemCatDubboService;

	@Override
	public EasyUIDataGrid listTbItemParamPage(int pageNum, int rows) {
		EasyUIDataGrid easydata = tbItemParamDubboService.listTbItemParamPage(pageNum, rows);
		List<TbItemParamCustom> retdata = new ArrayList<>(rows);
		@SuppressWarnings("unchecked")
		List<TbItemParam> listdata = (List<TbItemParam>) easydata.getRows();
		TbItemParamCustom custom = null;
		for(TbItemParam param:listdata){
			//因为返回数据缺少类别名称字段，在这里做转换
			custom = new TbItemParamCustom();
			try {
				BeanUtils.copyProperties(custom, param, true);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			custom.setItemCatName(tbItemCatDubboService.loadTbItemCatByPK(param.getItemCatId()).getName());
			retdata.add(custom);
		}
		
		easydata.setRows(retdata);
		return easydata;
	}

	@Override
	public boolean deleteTbItemByPK(String ids) throws DaoException{
		String[] idarray = ids.split(",");
		boolean t = true;
		for(String id:idarray){
			if(tbItemParamDubboService.delTbItemParamByPK(Long.parseLong(id))<=0){
				t = false;
				throw new DaoException("提示：id为["+id+"]的规格信息已被删除,请刷新后确认");
			}
		}
		if(t){
			return true;
		}
		return false;
	}


	@Override
	public boolean saveTbItemParam(long catId, String paramData) {
		TbItemParam tbItemParam = new TbItemParam();
		tbItemParam.setItemCatId(catId);
		tbItemParam.setParamData(paramData);
		Date date = new Date();
		tbItemParam.setCreated(date);
		tbItemParam.setUpdated(date);
		if(tbItemParamDubboService.saveTbItemParam(tbItemParam)>0){
			return true;
		}
		return false;
	}

	@Override
	public TbItemParam loadTbItemParamByCatId(long catId) {
		List<TbItemParam> listdata = tbItemParamDubboService.loadParamByCatId(catId);
		if(listdata!=null && !listdata.isEmpty()){
			return listdata.get(0);
		}
		return null;
	}
}
